package attribute

import (
	"context"
	// "fmt"
	"strings"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/product/model"
	"mall/service/product/rpc/internal/svc"
	"mall/service/product/rpc/internal/utils/errorhandler"
	"mall/service/product/rpc/types/product"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetAttributeListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetAttributeListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetAttributeListLogic {
	return &BackendGetAttributeListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendGetAttributeListLogic) BackendGetAttributeList(in *product.AttributeListReq) (*product.AttributeListResp, error) {
	// logx.Infof("BackendGetAttributeList : %+v ", in)
	// logrus.Info(fmt.Sprintf("BackendGetAttributeList: %+v", in))

	var orderBys []string
	if len(in.OrderBy) > 0 {
		for _, orderBy := range in.OrderBy {
			order := " ASC"
			if orderBy.Order == "1" {
				order = " DESC"
			}
			if orderBy.Field == "id" {
				orderBys = append(orderBys, model.AttributeColumns.ID+order)
			}
			if orderBy.Field == "sort" {
				orderBys = append(orderBys, model.AttributeColumns.Sort+order)
			}
			if orderBy.Field == "createdAt" {
				orderBys = append(orderBys, model.AttributeColumns.CreatedAt+order)
			}
		}
	}

	var stati string
	var attrType string
	if len(in.FilterBy) > 0 {
		for _, filterBy := range in.FilterBy {
			switch filterBy.Field {
			case "status":
				stati = filterBy.In
			case "type":
				attrType = filterBy.In
			}
		}
	}

	var page uint64
	var pageSize uint64
	var restricted bool
	var withCount int
	var preCount int64
	filterMap := make(map[string]map[string][]any)
	resp := &product.AttributeListResp{}
	if in.Ids != nil && len(*in.Ids) > 0 {
		if vals := modelx.UniqueInterfaces(*in.Ids, 64); len(vals) == 0 {
			return resp, nil
		} else {
			filterMap[model.AttributeColumns.ID] = map[string][]any{
				"in": vals,
			}
			restricted = true
			withCount = -1
			preCount = int64(len(vals))
		}
	}

	var statusIsSet bool
	var isAll bool
	statusMap := make(map[string][]any)
	switch attrType {
	case "1": // 全部
		statusMap["notEqualTo"] = []any{globalkey.StatusDeleted}
		isAll = true
	case "2": // 正常
		filterMap[model.AttributeColumns.Status] = map[string][]any{
			"equalTo": {globalkey.StatusNormal},
		}
		statusIsSet = true
	case "3": // 禁用
		filterMap[model.AttributeColumns.Status] = map[string][]any{
			"equalTo": {globalkey.StatusBanned},
		}
		statusIsSet = true
	case "4": // 回收站
		filterMap[model.AttributeColumns.Status] = map[string][]any{
			"equalTo": {globalkey.StatusDeleted},
		}
		statusIsSet = true
	}

	if !restricted {
		page = in.Page
		pageSize = in.PageSize
		withCount = 1
	}

	if in.Name != nil && len(strings.TrimSpace(*in.Name)) >= 2 {
		filterMap[model.AttributeColumns.Name] = map[string][]any{
			"contain": {strings.TrimSpace(*in.Name)},
		}
	}
	if in.Slug != nil && len(strings.TrimSpace(*in.Slug)) >= 2 {
		filterMap[model.AttributeColumns.Slug] = map[string][]any{
			"contain": {strings.TrimSpace(*in.Slug)},
		}
	}
	if in.IsVariation != nil {
		filterMap[model.AttributeColumns.IsVariationAttribute] = map[string][]any{
			"equalTo": {*in.IsVariation},
		}
	}

	var startTimeIn []any
	var endTimeIn []any
	if in.StartTime != nil && len(strings.TrimSpace(*in.StartTime)) > 0 {
		if startTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.StartTime)); err == nil {
			startTimeIn = append(startTimeIn, startTime)
		}
	}
	if in.EndTime != nil && len(strings.TrimSpace(*in.EndTime)) > 0 {
		if endTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.EndTime)); err == nil {
			endTimeIn = append(endTimeIn, endTime)
		}
	}
	createdAtMap := make(map[string][]any)
	if len(startTimeIn) > 0 {
		createdAtMap["moreThanOrEqualTo"] = startTimeIn
	}
	if len(endTimeIn) > 0 {
		createdAtMap["lessThan"] = endTimeIn
	}
	filterMap[model.AttributeColumns.CreatedAt] = createdAtMap

	var search string
	if in.Search != nil && len(strings.TrimSpace(*in.Search)) >= 2 {
		search = strings.TrimSpace(*in.Search)
	}

	// logrus.Info(fmt.Sprintf("BackendGetAttributeList filterMap: %+v", filterMap))

	if isAll {
		ret, _, err := l.svcCtx.Attribute.GetList(l.ctx, model.M{
			"search":    search,
			"statistic": "1",
		}, 5, filterMap)
		if err != nil {
			// return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			logx.Errorw("BackendGetAttributeList GetList statistic err", logx.Field("detail", err.Error()))
		} else if len(ret) > 0 {
			statusStatisticMap := make(map[uint32]uint32)
			var total uint64
			for _, v := range ret {
				statusStatisticMap[uint32(v.Status)] = uint32(v.Taxonomy)
				if v.Status != uint8(globalkey.StatusDeleted) {
					total += v.Taxonomy
				}
			}
			statusStatisticMap[uint32(4)] = uint32(total)
			resp.StatusStatisticMap = statusStatisticMap
		}
	}

	if !statusIsSet {
		// logrus.Info(fmt.Sprintf("BackendGetAttributeList in.Status: %+v", in.Status))
		statusIn := modelx.UniqueInterfaces(stati, 32)
		if len(statusIn) > 0 {
			statusMap["in"] = statusIn
		}
		if in.Status != nil {
			statusMap["equalTo"] = []any{*in.Status}
		}
		filterMap[model.AttributeColumns.Status] = statusMap
	}

	var orderBy string
	if len(orderBys) > 0 {
		orderBy = strings.Join(orderBys, ",")
	}
	res, count, err := l.svcCtx.Attribute.GetList(l.ctx, model.M{
		"page":     page,
		"pageSize": pageSize,
		"search":   search,
		"orderBy":  orderBy,
	}, withCount, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if restricted {
		count = preCount
	}
	resp.Total = uint64(count)

	if len(res) > 0 {
		var aids []any
		for _, v := range res {
			aids = append(aids, v.ID)
		}

		idOptionMap := make(map[uint64][]*product.AttributeOptionInfo)
		if in.WithOption != nil && *in.WithOption > 0 {
			subFilterMap := make(map[string]map[string][]any)
			subFilterMap[model.AttributeOptionColumns.AttributeID] = map[string][]any{
				"in": aids,
			}
			list, _, err := l.svcCtx.Attribute.GetOptionList(l.ctx, model.M{}, -1, subFilterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			if len(list) > 0 {
				for _, v := range list {
					idOptionMap[v.AttributeID] = append(idOptionMap[v.AttributeID], &product.AttributeOptionInfo{
						Id:          &v.OptionID,
						AttributeId: &v.AttributeID,
						Name:        &v.Name,
						Slug:        &v.Slug,
						Sort:        pointy.GetPointer(uint32(v.Sort)),
						Status:      pointy.GetPointer(uint32(v.Status)),
						CreatedAt:   pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
						UpdatedAt:   pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
						DeletedAt:   pointy.GetPointer(modelx.FormatNullDotTime(v.DeletedAt, "")),
					})
				}
			}
		}

		for _, v := range res {
			var opts []*product.AttributeOptionInfo
			if os, ok := idOptionMap[v.ID]; ok {
				opts = os[:]
			}

			resp.List = append(resp.List, &product.AttributeInfo{
				Id:          &v.ID,
				TermId:      &v.TermID,
				Taxonomy:    &v.Taxonomy,
				IsVariation: pointy.GetPointer(uint32(v.IsVariationAttribute)),
				Name:        &v.Name,
				Slug:        &v.Slug,
				HasMedia:    pointy.GetPointer(uint32(v.HasImage)),
				Sort:        pointy.GetPointer(uint32(v.Sort)),
				Status:      pointy.GetPointer(uint32(v.Status)),
				CreatedAt:   pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
				UpdatedAt:   pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
				DeletedAt:   pointy.GetPointer(modelx.FormatNullDotTime(v.DeletedAt, "")),
				Options:     opts,
			})
		}
	}

	return resp, nil
}
